package org.grow.later.upload;

import org.grow.later.download.ControllerDownload;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class ControllerUpload {
    @Resource
    private ControllerDownload controllerDownload;
    @Value("${upload.dir:upload}")
    private String uploadDir;

    @PostMapping("/upload")
    public ModelAndView uploadPage(@RequestParam MultipartFile file,
                                   HttpServletRequest request) throws IOException {
        ModelAndView mv = controllerDownload.mainFtpPage();

        if (file.isEmpty()) {
            mv.addObject("uploadResult",
                    "upload file is empty");
            return mv;
        }
        String s = file.getOriginalFilename();
        int sl = Math.min(s.length(),5);
        System.out.println(" upload a file: " +s.substring(0,sl)+"...");
        String fileName = System.currentTimeMillis() + "--" + s;
        Path dest = Paths.get(System.getProperty("user.home")).resolve(uploadDir);
        if (Files.notExists(dest)) Files.createDirectories(dest);
        dest = dest.resolve(fileName);
        if (Files.notExists(dest)) Files.createFile(dest);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            mv.addObject("uploadResult",
                    "failed upload file");
            return mv;

        }
        mv.addObject("uploadResult",
                "successfully upload file via IP: " + fileName);
        return mv;
    }

}
